package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.lifecycle.lifecycleScope
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.model.param.ConsumeParam
import com.gexiaobao.pigeon.app.model.param.PayParam
import com.gexiaobao.pigeon.app.model.param.ReSendSMSParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.FragmentCashierBinding
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/7/3 10:31
 * @Describe    : 收银台
 */
class FragmentCashier : BaseFragment<MallViewModel, FragmentCashierBinding>() {

    private var name = ""
    private var address = ""
    private var phone = ""
    private var intentType = ""
    private var id = 0
    private var payPassDialog: PayPassDialog? = null
    private var isResendCode: Boolean = false
    private var payDialog: RxPayDialog? = null
    private var isApply: Boolean = false//标记是否支付过
    private var isPaySuccess: Boolean = false//标记是否支付成功
    private var useGebi: Int = -1

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.tvWhiteTitle.text = getString(R.string.marker_shop_cashier)

        useGebi = requireArguments().getInt("useGebi")
        name = arguments?.getString("orderReceiver").toString()
        address = arguments?.getString("orderAddress").toString()
        phone = arguments?.getString("orderContactPhone").toString()
        intentType = arguments?.getString("intentType").toString()
        id = arguments?.getInt("orderId")!!
        isApply = arguments?.getBoolean("isApply")!!
        val price = requireArguments().getString("price").toString().trim()
        SettingUtil.setPrice(price, mDatabind.tvCashierTotalPrice, 80, Color.parseColor("#F44336"))

        //监听系统返回键
        activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!isPaySuccess) {
                    showHintDialog()
                } else {
                    nav().navigateUp()
                }
            }
        })
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvCashierPayment, mDatabind.includeBar.ivBack) {
            when (it) {
                mDatabind.includeBar.ivBack -> {
                    if (!isPaySuccess) {
                        showHintDialog()
                    } else {
                        nav().navigateUp()
                    }
                }

                mDatabind.tvCashierPayment -> {
                    isResendCode = false
                    shoppingMallConsumption()
                }
            }
        }
    }

    private fun showHintDialog() {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("订单暂未支付，确定离开？")
        dialog.setLeftBtnContent("继续支付")
        dialog.setRightBtnContent("确认离开")
        dialog.setSureListener {
            nav().popBackStack(R.id.fragmentOrderDetail, true)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun createObserver() {
        super.createObserver()
        /** 重新发送验证码  */
        mViewModel.reSendSMSResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                if (!isResendCode) {
                    showPayDialog()
                }
            } else {
                RxToast.showToast(it.errorMsg)
                if (it.errorMsg == "未绑定手机。") {
                    showErrorDialog()
                    return@observe
                }
            }
        }
        /** 确认支付 */
        mViewModel.payResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                payPassDialog?.dismiss()
                isPaySuccess = true
                if (payDialog != null && payDialog!!.isShowing)
                    payDialog?.showBottomView()
                paySuccess()
            }, {
                payDialog?.dismiss()
                RxToast.showToast(it.msg)
            })
        }
        /** 立即购买  */
        mViewModel.consumeResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                if (!isResendCode) {
                    showPayDialog()
                }
                isApply = true
            }, {
                RxToast.showToast(it.msg)
                if (it.msg == "未绑定手机。") {
                    showErrorDialog()
                    return@parseState
                }
            })
        }
    }

    private fun showErrorDialog() {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("您还未绑定手机！")
        dialog.setRightBtnContent("去绑定")
        dialog.setSureListener {
            nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                putString(Constant.INTO_TYPE, "mineBank")
            })
            dialog.dismiss()
        }
        dialog.setLeftBtnContent("再想想")
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun paySuccess() {
        eventViewModel.refundReturnResult.value = true
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent("支付成功")
        payDialog?.setSureBtnContent("查看订单")
        payDialog?.setCancelBtnContent("返回上一页")
    }

    @SuppressLint("SetTextI18n")
    private fun showPayDialog() {
        payPassDialog = PayPassDialog(context)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast("关闭支付")
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                isResendCode = true
                shoppingMallConsumption()
            }

            override fun onPassFinish(verifyCode: String?) {
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val body = PayParam(id, verifyCode.toString())
                    mViewModel.commitPay(body)
                }, lifecycleScope)
            }
        })
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(context)
        payDialog!!.loadingDialog()
        payDialog!!.setSureListener {
            /** 通知付款成功，刷新数据 */
            eventViewModel.toNoticePaySuccess.value = true
            if (intentType == "list") {
                nav().popBackStack(R.id.fragmentOrderDetail, true)
            } else {
                nav().navigateAction(R.id.action_to_fragment_mine_order, Bundle().apply {
                    putInt("orderIndex", 2)
                })
            }
            payDialog!!.dismiss()
        }
        payDialog!!.setCancelListener {
            /** 通知付款成功，刷新数据 */
            eventViewModel.toNoticePaySuccess.value = true
            try {
                payDialog!!.dismiss()
                nav().popBackStack(R.id.fragmentOrderDetail, true)
            } catch (_: Exception) {
            }
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }

    private fun shoppingMallConsumption() {
        showLoading(getString(R.string.loading))
        if (isApply) {//重新发送验证码
            val body = ReSendSMSParam(orderId = id)
            mViewModel.reSendSMS(body)
        } else {
            val body = ConsumeParam(orderReceiver = name, orderAddress = address, orderContactPhone = phone, orderId = id, useGebi = useGebi)
            mViewModel.consumeMallApply(body)
        }
    }
}